<template>
  <div class="setting-approve">
    <el-radio-group v-model="approveSetting.level" @change="beforeSwitch">
      <el-radio :label="0">{{$t('task.setting.taskTypeSetting.flow.components.noApprove')}}</el-radio>
      <el-radio v-if="!isCustomNode" :label="1" class="ml-12">{{$t('common.base.approveLevel', {data1: $t('common.base.number1')})}}</el-radio>
      <el-radio v-if="!isCustomNode" :label="2" class="ml-12">{{$t('common.base.approveLevel', {data1: $t('common.base.number2')})}}</el-radio>

      <template v-if="isShowVipApprove">
        <el-radio :label="4" class="ml-12">{{$t('common.base.heightApproveLevel')}}</el-radio>
      </template>
      <slot name="reassign"></slot>
    </el-radio-group>

    <!--S 一级审批设置 -->
    <div class="setting-ZQapprove-people" :style="widthStyle">
      <div class="approve-section" v-if="approveSetting.level >= 1 && approveSetting.level !==3 && approveSetting.level !==4 ">
        <el-row class="approve-title">
          <el-col :span="12">
            <span>
              {{$t('zhongqi.setting.firstLevelApprove')}}:
            </span>
          </el-col>
          <el-col :span="12">
            <div v-if="isShowCondition" @click="showApproveSetting(approveSetting.conditions, 1)" class="approve-title-bt">{{$t('zhongqi.setting.setApprovalConditions')}}</div>
          </el-col>
        </el-row>
    
        <el-tooltip :disabled="!approveSetting.leader || options.some(opt => approveSetting.leader === opt.value)" :content="$t('task.setting.taskTypeSetting.flow.components.tip1')">
          <el-select
            class="w-352 mr-5"
            :value="approveSetting.leader"
            :placeholder="$t('common.placeholder.select')"
            @change="(val) => updateApproveSetting('leader', val, 1)"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-tooltip>
        <template v-if="approveSetting.leader === 'users'">
          <el-input
            v-if="!isOpenData"
            class="w-240 mr-5"
            :placeholder="$t('task.tip.approveTip6')"
            readonly
            :value="getApproverNames(approveSetting.approvers)"
            @click.native="selectApproveUser(1)"
          />
          <div v-else class="setting-open-data-input block-inline w-187 mr-5" @click="selectApproveUser(1)">
            <template v-if="!approveSetting.approvers || !approveSetting.approvers.length"><span class="placeholder-text">{{$t('task.tip.approveTip6')}}</span></template>
            <template v-else v-for="(item, index) in getApproverIds(approveSetting.approvers)">
              <open-data :key="item" type="userName" :openid="item"></open-data>
              <ui-separator :index="index" :list="getApproverIds(approveSetting.approvers)" :key="`${item}${uuid()}`" />
            </template>
          </div>
        </template>

        <condition-list
          :conditionList="approveSetting.conditions ? approveSetting.conditions : defaultConditions"
        ></condition-list>
      </div>
      <!--E 一级审批设置 -->
      <!--S 二级以上审批设置 -->
      <div class="approve-section" v-if="approveSetting.level > 1 && approveSetting.level !==3 && approveSetting.level !== 4">
        <template >
          <el-row class="approve-title">
          <el-col :span="12">
            <span>
              {{$t('zhongqi.setting.secondaryApprover')}}:
            </span>
          </el-col>
          <el-col :span="12">
            <div v-if="isShowCondition" @click="showApproveSetting(defaultConditions, 2)" class="approve-title-bt">{{$t('zhongqi.setting.setApprovalConditions')}}</div>
          </el-col>
        </el-row>
        <div
            v-for="(setting, idx) in approveSetting.multiApproverSetting"
            :key="idx"
          >
            <el-tooltip :disabled="!approveSetting.multiApproverSetting[idx].leader || options.some(opt => approveSetting.multiApproverSetting[idx].leader === opt.value)" :content="$t('task.setting.taskTypeSetting.flow.components.tip1')">
              <el-select
                class="w-352 mr-5"
                :value="setting.leader"
                :placeholder="$t('common.placeholder.select')"
                @change="(val) => updateApproveSetting('leader', val, idx + 2)"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
                
              </el-select>
            </el-tooltip>
            <template v-if="setting.leader === 'users'">
              <el-input
                v-if="!isOpenData"
                class="w-187"
                :placeholder="$t('task.tip.approveTip6')"
                readonly
                :value="getApproverNames(setting.approvers)"
                @click.native="selectApproveUser(idx + 2)"
              />
              <div v-else-if="isOpenData" class="setting-open-data-input block-inline w-187" @click="selectApproveUser(idx + 2)">
                <template v-if="!setting.approvers || !setting.approvers.length"><span class="placeholder-text">{{$t('task.tip.approveTip6')}}</span></template>
                <template v-else v-for="(item, index) in getApproverIds(setting.approvers)">
                  <open-data :key="item" type="userName" :openid="item"></open-data>
                  <ui-separator :index="index" :list="getApproverIds(setting.approvers)" :key="`${item}${uuid()}`" />
                </template>
              </div>
            </template>
          </div>
        </template>
        <!-- 二级审批目前只有一级 -->
        <condition-list
          :conditionList="multiApproverSettingLength ? approveSetting.multiApproverSetting[0].conditions : defaultConditions"
        ></condition-list>
      </div>
      
      <div class="approve-paas" v-if="approveSetting.level === 4">
        <div class="approve-paas-title">
          <div class="title-detail">{{$t('common.zhongqi.approvalProcess')}}</div> 
          <el-button type="primary" @click="editFlow">{{$t('common.zhongqi.setApprove')}}</el-button>
        </div> 
        <template>
          <div class="paas-preview" v-loading="loadingShow">
            <iframe v-if="reloadIframe" id="paasIframe" ref="iframePage" :src="iframeUrl" height="500px" width="100%" @load="loadingShow = false" />
          </div>
        </template>
      </div>
      <!--E 二级以上审批设置 -->
    </div>


    <base-window
      :title="$t('common.zhongqi.setApprovalProcess')"
      size="large"
      width="800px"
      :sizeData="{ minWidth: 1060, minHeight: 650 }"
      :show.sync="heightApproveLevelDia"
      className="work-flow-approve"
      >
      <div class="paas-wrap" v-loading="editloadingShow">
        <iframe id="frame_heightApprove" ref="iframePageEdit" :src="iframeEditUrl" height="100%" width="100%" @load="editloadingShow = false"/>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="heightApproveLevelDia = false">{{$t('common.base.cancel')}}</el-button>
        <el-button :disabled="pending" type="primary" @click="savePaasResult">{{ $t('common.base.makeSure') }}</el-button>
      </span>
    </base-window>


    <approve-setting-criteria 
    ref="ApprovalSettingCriteria" 
    :task-type-id="taskTypeId" 
    :flowType="flowType"
    :isFromAdvanced="isFromAdvanced"
    :optionMaps="optionMaps"
    @getCondition="getCondition"
    ></approve-setting-criteria>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'
import _ from 'lodash';
import TaskApprover from '@model/types/setting/task/TaskApprover';
import ApproveSettingCriteria from './ApproveSettingCriteria.vue'
import ConditionList from './ConditionList.vue'
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'
import { getRootWindow } from '@src/util/dom';
import { reDeployment, createVipApproveFlow, updateProcess } from '@src/api/TaskApi.ts';

const CreateUuid = () => URL.createObjectURL(new Blob()).substr(-36);


export default {
  name: 'approve-setting',
  props: {
    options: {
      type: Array,
      default: () => [],
    },
    optionMaps: {
      type: Object,
      default: () => ({})
    },
    approveSetting: {
      type: Object,
      default: () => new TaskApprover(),
    },
    taskTypeId: {
      type: String,
      default: ''
    },
    flowType: {
      type: String,
      default: ''
    },
    flowTypeStr: {
      type: String,
      default: ''
    },
    isUpdate: {
      type: Boolean,
      default: false
    },
    isFromAdvanced: {
      type: Boolean,
      default: false
    },
    // 是否自定义节点
    isCustomNode: {
      type: Boolean,
      default: false
    },
    // 是否公共节点
    isCommonNode: {
      type: Boolean,
      default: false
    },
    // 当前自定义节点是否新添加的节点（）
    isNewNormalNode: {
      type: Boolean,
      default: false
    },
    // 当前节点id
    currentNodeId: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      compId: CreateUuid(),
      isOpenData,
      styleStr: '',
      defaultConditions: [],
      isShow: false,
      iframeUrl: '',
      iframeEditUrl: '', // 编辑的url
      heightApproveLevelDia: false,
      approveJson: {},
      paasIds: {
        appId: null,
        formTemplateId: null,
      },
      loadingShow: false,
      reloadIframe: true,
      editloadingShow: false, // 编辑加载
      pending: false,
    }
  },
  components: {
    [ApproveSettingCriteria.name]: ApproveSettingCriteria,
    [ConditionList.name]: ConditionList,
  },
  computed: {
    multiApproverSettingLength() {
      return (this.approveSetting.multiApproverSetting && this.approveSetting.multiApproverSetting[0] && this.approveSetting.multiApproverSetting[0].conditions && this.approveSetting.multiApproverSetting[0].conditions.length > 0)
    },
        
    widthStyle(){
      let style = {};
      style.maxWidth = '100%';
      return style;
    },
    // 重汽灰度
    isShowCondition() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskApproveCondition || false
    },

    isShowVipApprove() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskVipApprove || false
    }
  },
  watch: {
    approveSetting: {
      deep: true,
      handler(val) {
        // 先让iframe销毁
        this.reloadIframe = false;
        this.iframeUrl = null
        this.$nextTick(() => {
          if (this.approveSetting.vipApproveSetting?.appId && this.approveSetting.vipApproveSetting?.formTemplateId) {
            const {appId, formTemplateId} = this.approveSetting.vipApproveSetting
            this.paasIds = this.approveSetting.vipApproveSetting
            // 赋值地址，再加载
            this.iframeUrl = `/paas/#/workflow?appId=${appId}&formId=${formTemplateId}&taskTypeId=${this.taskTypeId}&taskFlowType=${this.flowType}&mode=preview`
          }
          this.reloadIframe = true;
        })
      }
    }
  },
  mounted() {
    let that = this
    // 高级审批灰度
    if (this.isShowVipApprove) {
      function onMessageCall(event) {
        const { data, action, compId, errMsg } = event.data
        // 判断是否是当前组件发起的请求
        if (compId !== that.compId) { return }

        // 判断审批节点是否没有选择审批人
        if(errMsg?.length) {
          return that.$alert(errMsg?.join('</br>'), that.$t('common.base.toast'), {
            dangerouslyUseHTMLString: true
          })
        }

        if(action === 'PaaS.frame.returnPaaSWorkflow') {
          const { flowData, currentVersion, nodeStyle } = _.cloneDeep(data)
          that.approveJson = flowData
          let params = {
            nodeStyle,
            antvJson: that.approveJson || {},
            workflowTemplateId: currentVersion?.bizId || '',
            ...that.paasIds
          }
          updateProcess(params).then((res) => {
            that.pending = false
            if (res.success) {
              that.$nextTick(() => {
                that.$refs.iframePage.contentWindow.location.reload(true)
              })
              that.heightApproveLevelDia = false
            } else {
              that.$platform.notification({
                title: res.message,
                type: 'error'
              });
            }
          })
        }
      }
      window.addEventListener('message', onMessageCall);
      this.$once('hook:beforeDestroy', () =>  window.removeEventListener('message', onMessageCall))


      // 初始化level是4的话，并且是第一次初始化的话 就请求接口
      if (this.approveSetting.vipApprove) {
        this.toShowApproveVip()
      } else {
        if (this.approveSetting.level === 4 && !this.approveSetting.vipApprove) {
          this.getInitData()
        } 
      }
    }
  },
  methods: {
    toShowApproveVip() {
      this.approveSetting.vipApprove = 1
      const {appId, formTemplateId} = this.approveSetting.vipApproveSetting
      this.paasIds = this.approveSetting.vipApproveSetting
      this.iframeUrl = `/paas/#/workflow?appId=${appId}&formId=${formTemplateId}&taskTypeId=${this.taskTypeId}&taskFlowType=${this.flowType}&mode=preview`
      this.iframeLoad()
    },
    getInitData() {
      let params = {
        taskTypeId: this.taskTypeId,
        node: this.flowTypeStr ? this.flowTypeStr : this.flowType,
        isExtendNode: this.isCustomNode,
      }

      createVipApproveFlow(params).then((res) => {
        if (res.success) {
          this.paasIds = res.result

          // 设置为高级审批
          this.approveSetting.vipApprove = 1
          this.approveSetting.vipApproveSetting = res.result
          this.iframeUrl = `/paas/#/workflow?appId=${res.result.appId}&formId=${res.result.formTemplateId}&taskTypeId=${this.taskTypeId}&taskFlowType=${this.flowType}&mode=preview`
          this.iframeLoad()
          // 自定义节点数据更新
          this.isCustomNode && this.$emit('change',  this.approveSetting);
        }
      })
    },

    iframeLoad() {
      this.loadingShow = true;
      const iframe = this.$refs.iframePage;
      if (iframe?.attachEvent) { // IE
        iframe.attachEvent('onload', () => { this.loadingShow = false; });
      } else { // 非IE
        iframe.onload =  () => { this.loadingShow = false; };
      }
    },

    formatNumToCN(num) {
      let changeNum = [
        this.$t('common.base.number0'),
        this.$t('common.base.number1'),
        this.$t('common.base.number2'),
        this.$t('common.base.number3'),
        this.$t('common.base.number4'),
        this.$t('common.base.number5'),
        this.$t('common.base.number6'),
        this.$t('common.base.number7'),
        this.$t('common.base.number8'),
        this.$t('common.base.number9')
      ];

      return changeNum[num];
    },
    editFlow() {
      // 不知道为啥appId没了，再次赋值
      !this.paasIds.appId ? this.paasIds = this.approveSetting.vipApproveSetting : ''
      // 打开paas配置多加三个参数isCustomNode：是否是自定义节点，currentNodeId：当前节点的id，isCommonNode：是否是公共节点
      this.iframeEditUrl = `/paas/#/workflow?appId=${this.paasIds.appId}&formId=${this.paasIds.formTemplateId}&taskTypeId=${this.taskTypeId}&taskFlowType=${this.flowType}&isCustomNode=${this.isCustomNode ? 'isCustomNode' : ''}&currentNodeId=${this.currentNodeId}&isCommonNode=${this.isCommonNode ? '1' : ''}`
      this.heightApproveLevelDia = true
      this.editloadingShow = true
    },

    savePaasResult() {
      this.pending = true
      let iframe = this.$refs.iframePageEdit.contentWindow;
      let message = {
        action: 'shb.frame.getPaaSWorkflow',
        compId: this.compId
      };
      iframe.postMessage(message, '*')
    },

    async beforeSwitch(val) {
      try {
        if(this.isNewNormalNode && val === 4) {
          this.approveSetting.level = 0;
          await this.$confirm(this.$t('event.setting.serviceEventTypeSetting.flow.tips2'), '', {
            confirmButtonText: this.$t('common.base.save'),
            cancelButtonText: this.$t('common.base.notSaveForNow'),
            type: 'warning',
            closeOnClickModal: false
          })
          this.$eventBus.$emit('task_custom_node_save', true, () => this.switchLevel(val));
        }else {
          this.switchLevel(val)
        }
      } catch (e) {
        console.error(e)
      }
    },
    /** 选择审批等级 */
    switchLevel(val) {
      this.approveSetting.level = val

      // leader为none的情况
      if (this.approveSetting && (this.approveSetting.leader === 'none')) {
        this.$set(this.approveSetting, 'leader', '')
      }

      if (!this.approveSetting.conditions) {
        this.$set(this.approveSetting, 'conditions', [])
      }
    
      if (!this.approveSetting.multiApproverSetting || this.approveSetting.multiApproverSetting.length === 0) {
        this.$set(this.approveSetting, 'multiApproverSetting', [
          {
            leader: '',
            approvers: [],
            conditions: []
          }
        ]);
      }

      if (val === 4) {
        this.$set(this.approveSetting, 'approvers', [])
        if (!this.iframeUrl) {
          // approveSetting有值取之前配置的审批流程
          if(this.approveSetting.vipApproveSetting?.appId && this.approveSetting.vipApproveSetting?.formTemplateId) {
            this.toShowApproveVip()
          }else {
            this.getInitData()
          }
        }
      } else {
        this.approveSetting.vipApprove = 0
      //  this.approveSetting.vipApproveSetting = {}
        // 自定义节点数据更新
        this.isCustomNode && this.$emit('change',  this.approveSetting);
      }
    },

    // 展示审批条件弹窗
    showApproveSetting(conditions, level) {
      if (level === 2) {
        if (this.multiApproverSettingLength) {
          conditions = this.approveSetting.multiApproverSetting[0].conditions
        } else {
          conditions = []
        }
      }
      this.$refs.ApprovalSettingCriteria.openDialog(conditions, level)
    },
    getApproverNames(approvers) {
      return approvers.map((item) => item.displayName).join(',');
    },
    getApproverIds(approvers) {
      return approvers.map((item) => item.staffId);
    },

    getCondition(val, level) {
      this.updateApproveSetting('conditions', val, level);
    },
    /**
     * 更新审批设置
     *
     * @param {string} key 更新的key值
     * @param {string} value 更新值
     * @param {number} level 更新审批的层级
     */
    updateApproveSetting(key, value, level) {
      let approveSetting = _.cloneDeep(this.approveSetting);

      // 一级设置
      if (level <= 1) {
        approveSetting[key] = value;
        if (approveSetting.leader !== 'users') {
          approveSetting.approvers = [];
        }
      }
      // 多级设置
      if (level > 1) {
        let multiApproverSetting = approveSetting.multiApproverSetting[level - 2];
        multiApproverSetting[key] = value;
        if (multiApproverSetting.leader !== 'users') {
          multiApproverSetting.approvers = [];
        }
      }

      this.$emit('change', approveSetting);
    },
    /**
     * 选择指定的审批人员
     * @param {number} level 审批的层级
     */
    selectApproveUser(level) {
      let selected = level < 2
        ? this.approveSetting.approvers
        : this.approveSetting.multiApproverSetting[level - 2].approvers;
      let options = {
        title: this.$t('task.tip.approveTip6'), // [选填] 默认值为 '请选择人员'
        max: 14, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        mode: BaseSelectUserModeEnum.Filter
      };

      this.$fast.select.multi.user(options)
        .then((res) => {
          if (res.status != 0) return;

          this.updateApproveSetting('approvers', res.data.users, level);
        })
        .catch((err) => {
          console.warn(err);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
// 企微端样式
@import '@src/modules/setting/openData.scss';

.paas-wrap {
  width: 100%;
  height: 100%;
}
.paas-preview {
  border-radius: 4px;
  padding: 10px 12px;
  background: #F2F2F2;
  cursor: pointer;
}

.approve-paas-title {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
  line-height: 30px;
  .title-detail {
    color: #333333d1;
    font-size: 14px;
    font-weight: bolder;
  }
}


.setting-approve {
  &-people {
    line-height: 40px;
    margin-bottom: 12px;
    font-size: 14px;
    color: #999999;
  }
}
.setting-ZQapprove-people {
  min-width: 390px;
  margin: 10px 0;
  // max-width: 100%;
  .approve-section {
    padding: 10px 12px;
    background: #F2F2F2;
    border-radius: 4px;
    margin-bottom: 12px;
  }


  .approve-title {
    color: #333333;
    line-height: 30px;
  }

  .approve-title-bt {
    color: $color-primary-light-6;
    text-align: right;
    cursor: pointer;
  }
}
.mr-5{
  margin-right: 5px;
}
.ml-5{
  margin-left: 5px;
}
.ml-12 {
  margin-bottom: 8px;
  // margin-left: 12px;
}

.mt-12 {
  margin-top: 12px;
}

.mb-12 {
  margin-bottom: 12px;
}

.w-352 {
  width: 100%;
  margin-bottom: 8px;
}
.block-inline {
  display: inline-block;
}
</style>

<style lang="scss">
.work-flow-approve {
  z-index: 1000 !important;
}
</style>
